package org.wutopia.labcloud.domain.file.controller;


import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.StatObjectArgs;
import io.minio.StatObjectResponse;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wutopia.labcloud.domain.file.controller.vo.input.FileDownloadUrlInputVO;
import org.wutopia.labcloud.library.common.base.CodedMessage;
import org.wutopia.labcloud.library.common.base.CommonResponse;
import org.wutopia.labcloud.domain.file.controller.vo.UploadUrlInputVO;
import org.wutopia.labcloud.service.api.service.dubbo.FileService;
import org.wutopia.labcloud.service.api.service.dubbo.dto.input.UploadUrlInputDTO;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@RestController
@AllArgsConstructor
@RequestMapping("/file")
@Slf4j
public class MinioFileController {

    private MinioClient minioClient;

    private FileService fileService;


    @PostMapping("/upload_url")
    public ResponseEntity<CodedMessage<String>> uploadUrl(@RequestBody UploadUrlInputVO vo)  {

        if( vo==null || vo.getObjectName() == null || vo.getBucketName() == null) {
            return CommonResponse.failure("入参错误");
        }
        log.info("upload_url input bucket: {}, objectName: {}", vo.getBucketName(),vo.getObjectName());
        // 生成上传链接（有效期 1 小时）
        UploadUrlInputDTO dto = new UploadUrlInputDTO();
        dto.setBucket(vo.getBucketName());
        dto.setObjectName(vo.getObjectName());

        String uploadUrl = fileService.getUploadUrl(dto);

        return CommonResponse.successWithData(uploadUrl);
    }

    @PostMapping("/download_url")
    public ResponseEntity<CodedMessage<String>> downloadUrl(@RequestBody FileDownloadUrlInputVO vo)  {

        try {

            // 检查对象是否存在
            StatObjectResponse statObjectResponse = minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(vo.getBucketName())
                            .object(vo.getObjectName())
                            .build()
            );
            if (statObjectResponse == null) {
                return null;
            }

            String url =  minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(vo.getBucketName())
                            .object(vo.getObjectName())
                            .expiry(1, TimeUnit.HOURS) // 1小时有效期
                            .build());

            return CommonResponse.successWithData(url);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | XmlParserException |
                 ServerException e) {
            log.error("获取文件下载链接失败: ", e);
            return null;
        }
    }
}
